package com.rainwood.water_authority.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.rainwood.water_authority.R;
import com.rainwood.water_authority.base.App;
import com.rainwood.water_authority.base.MyBaseActivity;
import com.rainwood.water_authority.helper.ActivityStackManager;
import com.rainwood.water_authority.helper.DoubleClickHelper;
import com.rainwood.water_authority.http.request.LogoutApi;
import com.rainwood.water_authority.http.request.PersonalDataApi;
import com.rainwood.water_authority.http.request.UpdateAppApi;
import com.rainwood.water_authority.http.response.PersonalDataBean;
import com.rainwood.water_authority.http.response.SimpleResultBean;
import com.rainwood.water_authority.http.response.UpdateResponse;
import com.rainwood.water_authority.model.CacheLoginBean;
import com.rainwood.water_authority.model.ModuleBean;
import com.rainwood.water_authority.ui.adapter.ModuleBaseAdapter;
import com.rainwood.water_authority.ui.dialog.MessageDialog;
import com.rainwood.water_authority.ui.dialog.UpdateDialog;
import com.rainwood.water_authority.ui.popup.ListPopup;
import com.rainwood.water_authority.util.Constants;
import com.rainwood.water_authority.util.LogUtils;
import com.rainwood.water_authority.util.SecuritySharedPreference;
import com.rainwood.water_authority.util.VersionUtils;
import com.sxs.easyhttp.EasyConfig;
import com.sxs.easyhttp.EasyHttp;
import com.sxs.easyhttp.listener.HttpCallback;
import com.sxs.tools.base.BaseAdapter;


import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author sxs
 * @date :2020/9/27
 * @desc: 首页
 */
public final class MainActivity extends MyBaseActivity implements BaseAdapter.OnItemClickListener {


    private TextView mPositionView;
    private TextView mNameView;
    private ImageView mHeadPhotoView,img_exit;
    private RecyclerView mModuleListView;

    private ModuleBaseAdapter mModuleAdapter;

    /**
     * 后台链接地址
     */
    private static String backgroundUrl;
    /**
     * 入库flag --- 处理广播处理两次的问题
     */
    private static boolean IN_STOCK_FLAG = true;
    /**
     * 发料flag --- 处理广播处理两次的问题
     */
    private static boolean ISSUE_FLAG = true;
    /**
     * 盘点flag --- 处理广播处理两次的问题
     */
    private static boolean INVENTORY_FLAG = true;
    private SecuritySharedPreference.SecurityEditor editor;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView() {
        editor = new SecuritySharedPreference(App.getContext(), null, MODE_PRIVATE).edit();
        mModuleListView = findViewById(R.id.rv_module_list);
        //个人信息
        mHeadPhotoView = findViewById(R.id.iv_head_photo);
        img_exit=findViewById(R.id.img_exit);
        mNameView = findViewById(R.id.tv_name);
        mPositionView = findViewById(R.id.tv_position);

        mModuleAdapter = new ModuleBaseAdapter(this);
        mModuleAdapter.setOnItemClickListener(this);
        mModuleListView.setAdapter(mModuleAdapter);

        // 延时注册广播
        postDelayed(this::registerReceiver, 1000);
        // 绑定扫码机
        // bindScannerService();
    }

    @Override
    protected void initData() {
        //组装首页模块数据
        int[] resDatums = {R.drawable.ic_in_storage, R.drawable.ic_store_issue,
                R.drawable.ic_inventory, R.drawable.ic_backstage};
        String[] names = {"收料", "发料", "盘点", "后台"};
        List<ModuleBean> moduleList = new ArrayList<>();
        for (int i = 0; i < resDatums.length; i++) {
            ModuleBean bean = new ModuleBean();
            bean.setRes(resDatums[i]);
            bean.setName(names[i]);
            moduleList.add(bean);
        }
        //设置数据
        mModuleAdapter.setData(moduleList);

        preference = new SecuritySharedPreference(App.getContext(), null, MODE_PRIVATE);
        // 查询数据库，设置token
        if (!TextUtils.isEmpty(preference.getString("loginCache", ""))) {
            CacheLoginBean cacheLogin = new Gson().fromJson(preference.getString("loginCache", ""), CacheLoginBean.class);
            if (cacheLogin != null&&!cacheLogin.equals("")) {
                EasyConfig.getInstance().addHeader("Auth", cacheLogin.getToken());
            }
        }
        img_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                        editor.putString("loginCache", "");
                editor.apply();

                EasyConfig.getInstance().addHeader("Auth","");
                startActivity(new Intent(MainActivity.this,LoginAty.class));
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestDatum();
    }

    private void requestDatum() {
        // 首页统计信息
        /*EasyHttp.post(this)
                .api(new HomeStaticsApi())
                .request(new HttpCallback<HomeStaticsBean>(this) {
                    @Override
                    public void onSucceed(HomeStaticsBean result) {
                        if (result.getCode() == 1 && result.getData() != null) {
                            if (mModuleAdapter.getData() != null) {
                                for (ModuleBean datum : mModuleAdapter.getData()) {
                                    switch (datum.getName()) {
                                        case "发料":
                                            datum.setBadge(result.getData().getSendNum());
                                            break;
                                        case "盘点":
                                            datum.setBadge(result.getData().getCheckNum());
                                            break;
                                        case "后台":
                                            backgroundUrl = result.getData().getBackstage();
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                mModuleAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });*/
        // 个人信息
        EasyHttp.post(this)
                .api(new PersonalDataApi())
                .request(new HttpCallback<PersonalDataBean>(this) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(PersonalDataBean result) {
                        if (result.getCode() == 1 && result.getData() != null) {
                            Glide.with(getContext())
                                    .load(result.getData().getIco())
                                    .circleCrop()
                                    .into(mHeadPhotoView);
                            mNameView.setText(result.getData().getName());
                            mPositionView.setText(result.getData().getJob());
                        }
                    }
                });
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        if (recyclerView.equals(mModuleListView)) {
            switch (mModuleAdapter.getItem(position).getName()) {
                case "收料":
                    ShouLiaoHomeAct.start(this);
                    break;
                case "发料":
                    FaLiaoHomeAct.start(this);
                    break;
                case "盘点":
                    PanDianHomeAct.start(this);
                    break;
                case "后台":
//                    https://www.yumukeji.cn/project/shuiwu/control/adIndex.php
//                    if (TextUtils.isEmpty(backgroundUrl)) {
//                        toast("当前没有后台");
//                        return;
//                    }
                    // 项目工程入口 "https://106.14.167.191/
                    BrowserBaseActivity.start(getActivity(), "https://www.yumukeji.cn/project/shuiwu/control/adIndex.php");
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onRightClick(View v) {
        // 菜单弹窗
        new ListPopup.Builder(this)
                .setList("退出登录", "检测更新")
                .addOnShowListener(popupWindow -> {

                })
                .addOnDismissListener(popupWindow -> {

                })
                .setListener((popupWindow, position, o) -> {
                    if (position == 0) {
                        new MessageDialog.Builder(getContext())
                                .setMessage("确定要退出登录吗？")
                                .setListener(dialog -> EasyHttp.post(MainActivity.this)
                                        .api(new LogoutApi())
                                        .request(new HttpCallback<SimpleResultBean>(MainActivity.this) {
                                            @Override
                                            public void onSucceed(SimpleResultBean result) {
                                                toast(result.getWarn());
                                                if (result.getCode() == 1) {
                                                    // 退出登录，跳转到登陆页面
                                                    postDelayed(() -> {
                                                        Application application = ActivityStackManager.getInstance().getApplication();
                                                        Intent intent = new Intent(application, LoginAty.class);
                                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                        application.startActivity(intent);
                                                        // 销毁除了登录页之外的界面
                                                        ActivityStackManager.getInstance().finishAllActivities(LoginAty.class);
                                                    }, 1000);
                                                }
                                            }
                                        })).show();
                    } else if (position == 1) {
                        // toast("检测更新");
                        EasyHttp.post(this)
                                .api(new UpdateAppApi())
                                .request(new HttpCallback<UpdateResponse>(this) {
                                    @Override
                                    public void onSucceed(UpdateResponse result) {
                                        Float version = (float) VersionUtils.getVersion(getContext());
                                        if (result.getData() != null) {
                                            if (version < result.getData().getVersion()) {
                                                String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                                        + getString(R.string.app_name) + "_v" + version + ".apk";
                                                VersionUtils.deleteLocal(new File(filePath));//删除旧的apk
                                                new UpdateDialog.Builder(getContext())
                                                        // 版本名
                                                        .setVersionName(VersionUtils.getVersionName(getContext()))
                                                        // 是否强制更新
                                                        .setForceUpdate("1".equals(result.getData().getForcedUpdat()))
                                                        // 更新日志
                                                        .setUpdateLog(result.getData().getName() + "\n" + result.getData().getUpdateTime())
                                                        // 下载 URL
                                                        .setDownloadUrl(result.getData().getSrc())
                                                        // 文件 MD5
                                                        //.setFileMd5("6ec99cb762ffd9158e8b27dc33d9680d")
                                                        .show();
                                            }
                                        }
                                    }
                                });
                    }
                })
                .showAsDropDown(v);
    }

    @Override
    public void onBackPressed() {
        if (DoubleClickHelper.isOnDoubleClick()) {
            // 移动到上一个任务栈，避免侧滑引起的不良反应
            moveTaskToBack(false);
            postDelayed(() -> {
                // 进行内存优化，销毁掉所有的界面
                ActivityStackManager.getInstance().finishAllActivities();
                // 销毁进程（注意：调用此 API 可能导致当前 Activity onDestroy 方法无法正常回调）
                // System.exit(0);

            }, 300);
        } else {
            toast(R.string.home_exit_hint);
        }
    }

    /**
     * 禁止侧滑
     */
    @Override
    public boolean isSwipeEnable() {
        return false;
    }

    /**
     * 动态广播
     */
    private static final String ACTION_DATA_CODE_RECEIVED =
            "com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED";
    private static final String DATA = "data";
    private static final String SOURCE = "source_byte";

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra(DATA);
            String arr = Arrays.toString(intent.getByteArrayExtra(SOURCE));
            if (code != null && !code.isEmpty()) {
                // 通过码去请求跳转的页面
                Activity topActivity = ActivityStackManager.getInstance().getTopActivity();
                LogUtils.d(TAG, "------ topActivity ------- " + topActivity);
                if (topActivity instanceof ShouLiaoHomeAct && IN_STOCK_FLAG) {
                    LogUtils.d(TAG, "-------- 扫码入库 ----" + code);
                    IN_STOCK_FLAG = !IN_STOCK_FLAG;
                    ShouLiaoListAct.start(getContext(), code);
                } else if (topActivity instanceof FaLiaoListAct && ISSUE_FLAG) {
                    LogUtils.d(TAG, "-------- 发料通知单 ----" + code);
                    ISSUE_FLAG = !ISSUE_FLAG;
                    IssueOutboundAty.start(getContext(), code, Constants.MATERIAL_ID);
                } else if (topActivity instanceof PanDianListAct && INVENTORY_FLAG) {
                    LogUtils.d(TAG, "-------- 物资盘点 ----" + code);
                    INVENTORY_FLAG = !INVENTORY_FLAG;
                    PanDianDetilsAct.start(getContext(), code, "scan");
                } else {
                    IN_STOCK_FLAG = true;
                    ISSUE_FLAG = true;
                    INVENTORY_FLAG = true;
                    // 关闭红外线
                    // unbindService(conn);
                }
            }
        }
    };

    private void registerReceiver() {
        LogUtils.d(TAG, "------ topActivity ------- " + 11111);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_DATA_CODE_RECEIVED);
        registerReceiver(receiver, filter);
    }

    /**
     * sunmi 扫码机
     */
//    public static IScanInterface scanInterface;
//    private static ServiceConnection conn = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
//            scanInterface = IScanInterface.Stub.asInterface(service);
//            LogUtils.i("setting", "Scanner Service Connected!");
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            LogUtils.e("setting", "Scanner Service Disconnected!");
//            scanInterface = null;
//        }
//    };
//
//    public void bindScannerService() {
//        Intent intent = new Intent();
//        intent.setPackage("com.sunmi.scanner");
//        intent.setAction("com.sunmi.scanner.IScanInterface");
//        //bindService(intent, conn, Service.BIND_AUTO_CREATE);
//    }
}